﻿using System.IO;
using System.IO.Compression;

namespace MIAPWEB.Common
{
    /// <summary>
    /// Clase de ayuda contenedora de funciones de compresión.
    /// </summary>
    public class CompressionHelper
    {
        /// <summary>
        /// Comprime un arreglo de <see cref="System.Byte"/>
        /// </summary>
        /// <param name="byteArray">Arreglo de <see cref="System.Byte"/> a comprimir</param>
        /// <returns>Un nuevo arreglo de <see cref="System.Byte"/> comprimido.</returns>
        public byte[] Compress(byte[] byteArray)
        {
            MemoryStream memoryStream = new MemoryStream();
            GZipStream zipStream = new GZipStream(memoryStream, CompressionMode.Compress, true);

            zipStream.Write(byteArray, 0, byteArray.Length);
            zipStream.Close();

            return memoryStream.ToArray();
        }

        /// <summary>
        /// Decomprime un arreglo de <see cref="System.Byte"/> previamente comprimido.
        /// </summary>
        /// <param name="byteArray">Arreglo de <see cref="System.Byte"/> a descomprimir.</param>
        /// <returns>Un nuevo arreglo de <see cref="System.Byte"/> descomprimido.</returns>
        public byte[] Decompress(byte[] byteArray)
        {
            MemoryStream memoryStream = new MemoryStream();
            GZipStream zipStream = new GZipStream(new MemoryStream(byteArray), CompressionMode.Decompress, true);

            byte[] buffer = new byte[4096];

            while (true)
            {
                int size = zipStream.Read(buffer, 0, buffer.Length);

                if (size > 0)
                {
                    memoryStream.Write(buffer, 0, size);
                }
                else
                {
                    break;
                }
            }

            zipStream.Close();

            return memoryStream.ToArray();
        }
    }
}